<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区域 -->
    <el-card>

      <!-- 卡片头部提示信息 -->
      <el-alert title="添加商品信息" type="info" center show-icon :closable="false">
      </el-alert>

      <!-- 进度条 -->
      <el-steps :space="200" :active="activeIndex - 0" finish-status="success" align-center>
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>

      <!-- tab标签 -->
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px" label-position="top">
        <el-tabs :tab-position="'left'" v-model="activeIndex" :before-leave="beforeTabLeave" @tab-click="tabClicked">
          <el-tab-pane label="基本信息">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="addForm.goods_price" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="addForm.goods_weight" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="addForm.goods_number" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <el-cascader v-model="addForm.goods_cat" :options="cateList" :props="sortProps" @change="handleChange">
              </el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数">
            <el-form-item :label="item.attr_name" v-for="item in paramsList" :key="item.attr_id">
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox :label="cb" v-for="(cb,i) in item.attr_vals" :key="i" border=""></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性">
            <el-form-item :label="item.attr_name" v-for="item in onlyparamsList" :key="item.attr_id">
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片">
            <el-upload class="upload-demo" :action="uploadUrl" :on-preview="handlePreview" :on-remove="handleRemove"
              :on-success="handleSuccess" list-type="picture" :headers="headerObj">
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容">
            <quill-editor v-model="addForm.goods_introduce" />
            <el-button type="primary" class="addGoods" @click="addGoods">添加商品</el-button>
          </el-tab-pane>
        </el-tabs>
      </el-form>

      <!-- 预览图片的对话框 -->
      <el-dialog title="预览图片" :visible.sync="previewVisible" width="50%">
        <img :src="previewUrl" alt="图片预览结果" style="width:100%">
      </el-dialog>

    </el-card>
  </div>
</template>
<script>
import _ from 'lodash'
export default {
  data () {
    return {
      activeIndex: '0',
      // tab标签form表单的数据对象
      addForm: {
        goods_name: '',
        goods_price: 0,
        goods_weight: 0,
        goods_number: 0,
        // 商品数据分类的双向绑定对象的id
        goods_cat: [],
        // 图片的数组
        pics: [],
        // 商品的参数（数组），包含 `动态参数` 和 `静态属性`
        attrs:[]
      },
      // tab标签form表单的数据对象的校验规则
      addFormRules: {
        goods_name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' },
        ],
        goods_price: [
          { required: true, message: '请输入商品价格', trigger: 'blur' },
        ],
        goods_weight: [
          { required: true, message: '请输入商品重量', trigger: 'blur' },
        ],
        goods_number: [
          { required: true, message: '请输入商品数量', trigger: 'blur' },
        ],
        goods_cat: [
          { required: true, message: '请输入商品分类', trigger: 'blur' },
        ],
      },
      // 商品数据列表
      cateList: [],
      // 商品级联选择框的商品分类的绑定数据对象
      sortProps: {
        expandTrigger: 'hover',
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
      },
      // 动态参数数据列表
      paramsList: [],
      // 静态数据列表
      onlyparamsList: [],
      // 上传图片的服务器地址
      uploadUrl: 'http://127.0.0.1:8888/api/private/v1/upload',
      // 上传图片的请求头配置对象
      headerObj: {
        Authorization: window.sessionStorage.getItem('token')
      },
      // 图片预览对话框的状态，默认关闭
      previewVisible: false,
      // 图片预览的地址
      previewUrl: ''
    }
  },
  created () {
    // 获取所有商品分类数据
    this.getCateList()
  },
  methods: {
    // 获取所有商品分类数据
    async getCateList () {
      const { data: res } = await this.$http.get('categories')

      if (res.meta.status !== 200) {
        return this.$message.error('获取商品分类数据失败！')
      }

      this.cateList = res.data
      console.log(this.cateList)
    },
    // 选中对应分类级联选择框触发
    handleChange () {
      console.log(this.addForm.goods_cat)
      if (this.addForm.goods_cat.length !== 3) {
        return this.addForm.goods_cat = []
      }
      else {
        return this.addForm.goods_cat
      }
    },
    // 切换标签之前的钩子
    beforeTabLeave (activeName, oldActiveName) {
      if (oldActiveName === '0' && this.addForm.goods_cat.length !== 3) {
        this.$message.error('请先选择商品分类')
        return false
      }
    },
    // tab 被选中时触发
    async tabClicked () {
      // 当选中参数tab，获取参数列表数据
      if (this.activeIndex === '1') {
        const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`, {
          params: { sel: 'many' }
        })
        if (res.meta.status !== 200) {
          return this.$message.error('获取动态参数失败')
        }
        res.data.forEach(item => {
          item.attr_vals = item.attr_vals.split(' ')
        });
        this.$message.success('获取动态参数成功')
        this.paramsList = res.data
        console.log(this.paramsList)
      }
      else if (this.activeIndex === '2') {
        const { data: res } = await this.$http.get(
          `categories/${this.cateId}/attributes`,
          {
            params: { sel: 'only' }
          }
        )

        if (res.meta.status !== 200) {
          return this.$message.error('获取静态属性失败！')
        }

        console.log(res.data)
        this.onlyparamsList = res.data
      }
    },
    // 文件列表移除文件时的钩子
    handleRemove (file) {
      // 找到图片临时地址
      const filePath = file.response.data.tmp_path
      // 根据图片地址找出在数组中的索引
      const i = this.addForm.pics.findIndex(re =>
        re.pic === filePath
      )
      // 根据索引删除数组的图片
      this.addForm.pics.splice(i, 1)
      console.log(this.addForm)

    },
    // 点击文件列表中已上传的文件时的钩子
    handlePreview (file) {
      console.log(file);
      this.previewUrl = file.response.data.url
      this.previewVisible = true


    },
    // 文件上传成功时的钩子
    handleSuccess (response) {
      console.log(response);
      // 图片临时地址对象
      const pic_info = { pic: response.data.tmp_path }
      // 把图片临时地址对象添加到pics图片数组中
      this.addForm.pics.push(pic_info)
      console.log(this.addForm)
    },
    // 点击添加商品按钮
    addGoods(){
      // 进行预验证
      this.$refs.addFormRef.validate(async valid =>{
        if(! valid){
          return this.$message.error('请填写完整必填相关信息')
        }
        // 对addForm深拷贝，复制出form对象
        const form = _.cloneDeep(this.addForm)
        // 把form里的goods_cat数组转换成字符串
        form.goods_cat = form.goods_cat.join(',')

        // 处理动态参数
        this.paramsList.forEach(item => {
          const newInfo = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals.join(' ')
          }
          this.addForm.attrs.push(newInfo)
        })
        // 处理静态属性
        this.onlyparamsList.forEach(item => {
          const newInfo = { attr_id: item.attr_id, attr_value: item.attr_vals }
          this.addForm.attrs.push(newInfo)
        })
        form.attrs = this.addForm.attrs
        console.log(form)
        // 发起请求添加商品
        // 商品的名称，必须是唯一的
        const { data: res } = await this.$http.post('goods', form)

        if (res.meta.status !== 201) {
          return this.$message.error('添加商品失败！')
        }

        this.$message.success('添加商品成功！')
        this.$router.push('/goods')

      })

    }
  },
  computed: {
    // 商品分类id
    cateId () {
      if (this.addForm.goods_cat.length === 3) {
        return this.addForm.goods_cat[2]
      }
    }
  }
}
</script>
<style lang="less" scoped>
.el-breadcrumb {
  margin-bottom: 20px;
  font-size: 12px;
}
.el-steps {
  margin-top: 10px;
}
.el-steps .el-steps--horizontal {
  text-align: center;
}
.addGoods{
  margin-top: 20px;
}
</style>
